<template>
  <el-dialog
    @close="closeDialog"
    v-model="dialogVisible"
    :title="title"
    :width="props.editType == 1 ? '400px' : '600px'"
  >
    <el-form
      ref="ruleFormRef"
      :model="formData"
      :rules="rules"
      label-width="90px"
      class="demo-ruleForm"
      status-icon
    >
      <div v-if="props.editType == 1">
        <el-form-item label="题库类型" prop="questionTypeName">
          <el-input v-model="formData.questionTypeName" maxlength="20" />
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-select v-model="formData.state" style="width: 100%">
            <el-option
              :value="item.value"
              :label="item.label"
              v-for="item in stateList"
              :key="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="formData.sort"
            :min="0"
            style="width: 100%"
          />
        </el-form-item>
      </div>
      <div v-else>
        <el-form-item label="题库类型:">
          {{ formData.questionTypeName }}
        </el-form-item>
        <el-form-item
          label="包含类型"
          prop="includeQuestionTypeIds"
          v-if="formData.id == 1 && props.editType == 2"
        >
          <el-select
            v-model="formData.includeQuestionTypeIds"
            multiple
            placeholder=""
            style="width: 100%"
          >
            <el-option
              v-for="item in typeList"
              :key="item.id"
              :label="item.questionTypeName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="测试时长:" prop="examTotal">
          <el-input v-model="formData.examTotal" maxlength="20">
            <template #append>分钟</template>
          </el-input>
        </el-form-item>
        <div class="box">
          <div>
            总题数：{{
              Number(formData?.singleChoiceTotal) +
              Number(formData?.multipleChoiceTotal) +
              Number(formData?.judgmentTotal)
            }}
          </div>
          <div>
            总分数：{{
              formData?.singleChoiceTotal * formData?.singleChoiceScore +
              formData?.multipleChoiceTotal * formData?.multipleChoiceScore +
              formData?.judgmentTotal * formData?.judgmentChoiceScore
            }}
          </div>
        </div>
        <el-row>
          <el-col :span="4">
            <el-form-item label="单选题:"></el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item label="数量:" prop="singleChoiceTotal">
              <el-input v-model="formData.singleChoiceTotal" />
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item label="每题分数:" prop="singleChoiceScore">
              <el-input v-model="formData.singleChoiceScore" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="4">
            <el-form-item label="多选题:"></el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item label="数量:" prop="multipleChoiceTotal">
              <el-input v-model="formData.multipleChoiceTotal" />
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item label="每题分数:" prop="multipleChoiceScore">
              <el-input v-model="formData.multipleChoiceScore" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="4">
            <el-form-item label="判断题:"></el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item label="数量:" prop="judgmentTotal">
              <el-input v-model="formData.judgmentTotal" />
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item label="每题分数:" prop="judgmentChoiceScore">
              <el-input v-model="formData.judgmentChoiceScore" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>
    <div class="footer">
      <el-button
        @click="submitForm(ruleFormRef)"
        type="primary"
        :loading="submitLoading"
      >
        保存
      </el-button>
      <el-button @click="closeDialog">取消</el-button>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, reactive, ref, watch } from "vue";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { ApiResult } from "@/util/request";
import {
  saveQuestionType,
  selectQuestionTypes,
  updateBatchQuestionType,
} from "@/api/system.ts";

interface IForm {
  id: string;
  sort: string;
  state: string;
  questionTypeName: string;
  includeQuestionTypeIds: [];
  judgmentChoiceScore: number;
  judgmentTotal: number;
  multipleChoiceScore: number;
  multipleChoiceTotal: number;
  singleChoiceScore: number;
  singleChoiceTotal: number;
  examTotal: number;
}
const stateList = [
  { value: "1", label: "启用" },
  { value: "2", label: "禁用" },
];
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  data: {
    type: Object,
    default: () => {},
  },
  editType: {
    type: String,
    default: () => "",
  },
  idList: {
    type: [],
    default: () => [],
  },
});

const emit = defineEmits(["update:visible", "update:data", "submit"]);

const ruleFormRef = ref();
const submitLoading = ref<boolean>(false);
const typeList = ref<[]>([]);

const formData = reactive<IForm>({
  id: "",
  sort: "1",
  state: "1",
  questionTypeName: "",
  includeQuestionTypeIds: [],
  judgmentChoiceScore: 0,
  judgmentTotal: 0,
  multipleChoiceScore: 0,
  multipleChoiceTotal: 0,
  singleChoiceScore: 0,
  singleChoiceTotal: 0,
  examTotal: 0,
});

//TODO 做成动态
const rules = reactive<FormRules<IForm>>({
  questionTypeName: [{ required: true, message: "请输入", trigger: "blur" }],
  examTotal: [{ required: true, message: "请输入", trigger: "blur" }],
  singleChoiceTotal: [{ required: true, message: "请输入", trigger: "blur" }],
  singleChoiceScore: [{ required: true, message: "请输入", trigger: "blur" }],
  multipleChoiceTotal: [{ required: true, message: "请输入", trigger: "blur" }],
  multipleChoiceScore: [{ required: true, message: "请输入", trigger: "blur" }],
  judgmentChoiceScore: [{ required: true, message: "请输入", trigger: "blur" }],
  judgmentTotal: [{ required: true, message: "请输入", trigger: "blur" }],
  includeQuestionTypeIds: [
    { required: true, message: "请选择", trigger: "change" },
  ],
});

const dialogVisible = computed({
  get() {
    return props.visible;
  },

  set(visible: boolean) {
    emit("update:visible", visible);
  },
});

//TODO 做成动态
const title = computed(() => {
  return props.editType == 1 ? "编辑" : "测试配置";
});

function closeDialog() {
  resetForm(ruleFormRef.value);
  emit("update:visible", false);
  emit("update:data", null);
}

async function getTypeList() {
  const { data, msg, success } = await selectQuestionTypes({
    isComprehensive: true,
  });
  if (!success) {
    ElMessage.error(msg);
    return;
  }
  typeList.value = data;
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    let result: ApiResult<any>;
    if (valid) {
      submitLoading.value = true;
      let api = saveQuestionType;
      let params = { ...formData };
      if (props.editType == "2" || props.editType == "3") {
        api = updateBatchQuestionType;
        params = { ...formData, id: props.idList };
      }
      result = await api(params);
      const { success, msg } = result;
      submitLoading.value = false;
      if (!success) {
        ElMessage.error(msg);
        return;
      }
      ElMessage.success("操作成功");
      closeDialog();
      emit("submit");
    } else {
      console.log("error submit!", fields);
    }
  });
};
watch(dialogVisible, async (visible) => {
  await getTypeList();
  Object.keys(formData).forEach((key: any) => {
    formData[key as keyof IForm] = visible ? props.data?.[key] || "" : "";
  });
  formData.sort = props.data?.sort ? props.data.sort : "1";
  formData.includeQuestionTypeIds = props.data?.includeQuestionTypeIds
    ? props.data.includeQuestionTypeIds
    : [];
  formData.state = props.data?.state ? props.data.state.toString() : "1";
});
</script>

<style scoped lang="scss">
.footer {
  width: 100%;
  text-align: center;
  margin-top: 50px;
}
.upload-demo {
  width: 100%;
}
.box {
  display: flex;
  width: 400px;
  height: 50px;
  font-size: 18px;
  line-height: 50px;
  margin: 5px auto;

  div {
    width: 200px;
  }
}
</style>
